package com.zw.yzk.kabu.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.model.ShoppingCartGoodsModel;
import com.zw.yzk.kabu.utils.CalculateUtils;
import com.zw.yzk.kabu.utils.ResUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by zhanwei on 2017/2/7.
 */

public class ShoppingCartGoodsListAdapter extends RecyclerView.Adapter<ShoppingCartGoodsListAdapter.Holder> {

    private List<ShoppingCartGoodsModel> dataList;
    private boolean editMode;
    private Context context;

    public ShoppingCartGoodsListAdapter(List<ShoppingCartGoodsModel> list, boolean mode) {
        dataList = new ArrayList<>();
        if (list != null) {
            dataList.addAll(list);
        }
        editMode = mode;
    }

    public void selectAll() {
        for (ShoppingCartGoodsModel model : dataList) {
            model.setSelected(true);
        }
        notifyDataSetChanged();
        if (listener != null && dataList.size() > 0) {
            listener.onTotalChanged(calculateTotalPrice(), dataList.get(0).getShopId(), calculateTotalPrice() == calculateTotalGoodsPrice());
        }
    }

    public void unSelectAll() {
        for (ShoppingCartGoodsModel model : dataList) {
            model.setSelected(false);
        }
        notifyDataSetChanged();
        if (listener != null && dataList.size() > 0) {
            listener.onTotalChanged(calculateTotalPrice(), dataList.get(0).getShopId(), calculateTotalPrice() == calculateTotalGoodsPrice());
        }
    }

    public void refresh(List<ShoppingCartGoodsModel> list, boolean mode) {
        dataList.clear();
        if (list != null) {
            dataList.addAll(list);
        }
        editMode = mode;
        notifyDataSetChanged();
    }

    public void changeMode(boolean mode) {
        editMode = mode;
        notifyDataSetChanged();
    }

    //计算所选商品总额
    private float calculateTotalPrice() {
        BigDecimal totalSum = new BigDecimal(0f);
        for (ShoppingCartGoodsModel model : dataList) {
            if (model.isSelected()) {
                BigDecimal price = new BigDecimal(model.getPrice());
                BigDecimal count = new BigDecimal(model.getCount());
                BigDecimal tmpSum = price.multiply(count);

                totalSum = totalSum.add(tmpSum);
            }
        }
        //四舍五入
        return CalculateUtils.setScale(totalSum, 2);
    }

    //计算所有商品总额
    private float calculateTotalGoodsPrice() {
        BigDecimal totalSum = new BigDecimal(0f);
        for (ShoppingCartGoodsModel model : dataList) {
            BigDecimal price = new BigDecimal(model.getPrice());
            BigDecimal count = new BigDecimal(model.getCount());
            BigDecimal tmpSum = price.multiply(count);

            totalSum = totalSum.add(tmpSum);
        }
        //四舍五入
        return CalculateUtils.setScale(totalSum, 2);
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_item_shopping_cart_goods_list, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(final Holder holder, int position) {
        ShoppingCartGoodsModel model = dataList.get(position);
        if (editMode) {
            holder.editState.setVisibility(View.VISIBLE);
            holder.changeCountLayout.setVisibility(View.VISIBLE);
            holder.goodsCount.setVisibility(View.GONE);
        } else {
            holder.editState.setVisibility(View.GONE);
            holder.changeCountLayout.setVisibility(View.GONE);
            holder.goodsCount.setVisibility(View.VISIBLE);
        }

        holder.name.setText(model.getGoodsName());
        holder.type.setText(model.getSelectedProperty());
        if (model.getPrice() != Float.MIN_NORMAL) {
            holder.price.setText(ResUtils.formatCurrency(context, model.getPrice()));
        }
        holder.goodsCount.setText(context.getResources().getString(R.string.goods_count, model.getCount()));
        holder.count.setText(String.valueOf(model.getCount()));
        holder.select.setChecked(model.isSelected());

        Glide.with(context)
                .load(model.getImage())
                .error(R.drawable.im_default)
                .into(holder.image);

        holder.editState.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                if (listener != null) {
                    listener.editGoods(dataList.get(position));
                }
            }
        });

        holder.select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                dataList.get(position).setSelected(!dataList.get(position).isSelected());

                if (listener != null) {
                    listener.onTotalChanged(calculateTotalPrice(), dataList.get(0).getShopId(), calculateTotalPrice() == calculateTotalGoodsPrice());
                }
            }
        });

        holder.decrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                int count = dataList.get(position).getCount();
                if (count <= 1) {
                    return;
                }
                dataList.get(position).setCount(count - 1);
                holder.goodsCount.setText(context.getResources().getString(R.string.goods_count, count - 1));
                holder.count.setText(String.valueOf(count - 1));

                if (listener != null) {
                    listener.onTotalChanged(calculateTotalPrice(), dataList.get(0).getShopId(), calculateTotalPrice() == calculateTotalGoodsPrice());
                }
            }
        });

        holder.increase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                int count = dataList.get(position).getCount();
                if (count >= 10) {
                    return;
                }
                dataList.get(position).setCount(count + 1);
                holder.goodsCount.setText(context.getResources().getString(R.string.goods_count, count + 1));
                holder.count.setText(String.valueOf(count + 1));

                if (listener != null) {
                    listener.onTotalChanged(calculateTotalPrice(), dataList.get(0).getShopId(), calculateTotalPrice() == calculateTotalGoodsPrice());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }


    public static class Holder extends RecyclerView.ViewHolder {

        @Bind(R.id.select)
        CheckBox select;
        @Bind(R.id.image)
        ImageView image;
        @Bind(R.id.name)
        TextView name;
        @Bind(R.id.type)
        TextView type;
        @Bind(R.id.edit_state)
        ImageView editState;
        @Bind(R.id.price)
        TextView price;
        @Bind(R.id.change_count_layout)
        View changeCountLayout;
        @Bind(R.id.decrease)
        TextView decrease;
        @Bind(R.id.increase)
        TextView increase;
        @Bind(R.id.count)
        TextView count;
        @Bind(R.id.goods_count)
        TextView goodsCount;

        public Holder(View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnTotalChangedListener {
        void onTotalChanged(float total, int shopId, boolean selectAll);

        void editGoods(ShoppingCartGoodsModel model);
    }

    private OnTotalChangedListener listener;

    public void setOnTotalChangedListener(OnTotalChangedListener listener) {
        this.listener = listener;
    }
}
